#include <stdio.h>

const int NAME_LEN = 20;

typedef struct _Student
{
    char name[NAME_LEN];
    int gender;
    int age;
} Student;

void saveStudent(Student students[], int stuNum) {
    FILE *f = fopen("student.data", "w");
    if (f)
    {
        fwrite(students, sizeof(Student), stuNum, f);
        fclose(f);
    }
}

void getStudentList(Student students[], int stuNum) {
    // 名称格式化输入
    char nameFormat[NAME_LEN];
    sprintf(nameFormat, "%%%ds", NAME_LEN-1);

    for (int i = 0; i < stuNum; i++) {
        // Student stu = *(students[i]);
        printf("输入姓名：");
        scanf(nameFormat, &students[i].name);

        printf("输入性别（1-女；2-男）：");
        scanf("%d", &students[i].gender);

        printf("输入年龄：");
        scanf("%d", &students[i].age);
    }
}

void recordStudent() {
    printf("输入学生个数：");
    int stuNum;
    scanf("%d", &stuNum);
    Student sutdents[stuNum];

    getStudentList(sutdents, stuNum);
    saveStudent(sutdents, stuNum);
    printf("End");
}

void printStu(Student stu) {
    const char * gender = "";//(stu.gender == 1 : "female" ? "male");
    if (stu.gender == 1)
    {
        gender = "female";
    } else {
        gender = "male";
    }
    
    printf ("{\n"
    "\tname=>%s\n"
    "\tage=>%d\n"
    "\tgender=>%s\n"
    "}\n", 
    stu.name,
    stu.age,
    gender
    );
}

void searchStudent() {
    FILE *f = fopen("student.data", "r");
    fseek(f, 0, SEEK_END);
    int size = ftell(f);
    int num = size/sizeof(Student);
    printf("number of Students is %d\n", num);

    printf("输入查找的学生所在位置\n");
    int pos;
    scanf("%d", &pos);

    if (pos >= num)
    {
        printf("超出范围\n");
        return;
    }
    

    fseek(f, pos * sizeof(Student), SEEK_SET);

    Student stu;
    fread(&stu, sizeof(Student), 1, f);
    printStu(stu);


    fclose(f);
}


int main() {
    // recordStudent();
    searchStudent();
    return 0;
}